package com.designpatterns.proxy.protect;

import java.lang.reflect.*;

/**
 * @author Brook
 */
public class OwnerInvocationHandler implements InvocationHandler{
    PersonBean personBean;

    public OwnerInvocationHandler(PersonBean personBean) {
        this.personBean = personBean;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException {
        try {
            if(method.getName().startsWith("get")){
                return method.invoke(personBean,args);
            } else if (method.getName().equals("setHotOrNotRating")) {
                throw new IllegalAccessException();
            } else if (method.getName().startsWith("set")){
                return method.invoke(personBean,args);
            }
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    public PersonBean getOwnerProxy(PersonBean personBean) {
        return (PersonBean) Proxy.newProxyInstance(personBean.getClass().getClassLoader(), personBean.getClass().getInterfaces(), (java.lang.reflect.InvocationHandler) new OwnerInvocationHandler(personBean));
    }
}
